package com.second.hand.trading.server.service.impl;

import com.second.hand.trading.server.Exception.BusinessException;
import com.second.hand.trading.server.dao.IntergralMapper;
import com.second.hand.trading.server.domain.Intergral;
import com.second.hand.trading.server.domain.User;
import com.second.hand.trading.server.enums.IntergralTypeEnum;
import com.second.hand.trading.server.service.IntergralDemoService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class IntergralServiceDemoImpl implements IntergralDemoService {

    private final IntergralMapper intergralMapper;
    private final HttpSession session;

    public IntergralServiceDemoImpl(IntergralMapper intergralMapper, HttpSession session) {
        this.intergralMapper = intergralMapper;
        this.session = session;
    }

    @Override
    public void incrIntergral(String token) {
        //1.根据token获取用户信息
        User loginUser = (User) session.getAttribute(token);
        //2.判断用户是否已经登录
        if (loginUser == null) {
            throw new BusinessException("请先登录");
        }
        //3.判断该用户今天是否已经签到,如果用户已经登录，则给用户增加积分1
        int row = intergralMapper.incrAccount(loginUser.getAccountNumber());
        if (row <= 0) {
            throw new BusinessException("今天已经签到");
        }
    }

    @Override
    public Intergral getIntergral(String token) {
        //1.根据token获取用户信息
        User loginUser = (User) session.getAttribute(token);
        //2.判断用户是否已经登录
        if (loginUser == null) {
            throw new BusinessException("请先登录");
        }
        //3.判断是否存在该用户积分记录
        Intergral intergral = intergralMapper.getByPhone(loginUser.getAccountNumber());
        if (intergral == null){
            intergralMapper.insert(loginUser.getAccountNumber(),0L);
        }
        //4.根据手机号获取到用户签到积分信息
        return intergralMapper.getByPhone(loginUser.getAccountNumber());
    }

    @Override
    public void decr(String token, Integer type) {
        //1.根据token获取用户信息
        User loginUser = (User) session.getAttribute(token);
        //2.判断用户是否已经登录
        if (loginUser == null) {
            throw new BusinessException("请先登录");
        }
        //3.判断积分是否足够，如果积分足够，进行积分扣除
        int row = 0;
        if(IntergralTypeEnum.TEN.getType().equals(type)){
            row = intergralMapper.decr(loginUser.getAccountNumber(), IntergralTypeEnum.TEN.getAmount());
        }else if(IntergralTypeEnum.ONE.getType().equals(type)){
            row = intergralMapper.decr(loginUser.getAccountNumber(), IntergralTypeEnum.ONE.getAmount());
        }
        if(row <= 0){
            throw new BusinessException("积分不足");
        }
    }
}
